package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = IUserService.class)
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Autowired
    private IRoleDao roleDao;

    @Autowired
    private IPermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {

        if (username == null){
            return null;
        }
        User user = userDao.findByUsername(username);
        if (user == null){
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roleList = roleDao.findByUserId(userId);
        user.setRoles(roleList);

        if (roleList != null && roleList.size() > 0) {

            for (Role role : roleList) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                role.setPermissions(permissions);
            }
        }

        return user;
    }

    /**
     * 分页查找功能
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.findPage(queryString);
        long total = page.getTotal();
        List<User> rows = page.getResult();
        return new PageResult(total,rows);
    }


    /**
     * 添加用户
     * @param user
     * @param roleIds
     */
    @Override
    public void add(User user, Integer[] roleIds) {
        String originPassword = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(originPassword);
        user.setPassword(password);
        // 添加用户
        userDao.add(user);
        // 建立用户与角色的关联
        this.setUserAndRole(user.getId(),roleIds);
    }

    /**
     * 根据ID查询用户
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        User user = userDao.findById(id);
        return user;
    }

    /**
     * 编辑功能
     * @param user
     * @param roleIds
     */
    @Override
    public void edit(User user, Integer[] roleIds) {
        userDao.edit(user);
        // 删除原角色和用户的关联
        userDao.deleteAssociation(user.getId());
        // 建立角色和用户新关联
        this.setUserAndRole(user.getId(),roleIds);
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void delete(Integer id) {
        // 删除用户和角色的关联
        userDao.deleteAssociation(id);
        userDao.delete(id);
    }

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<User> findAll() {
        List<User> list = userDao.findAll();
        return list;
    }

    // 建立用户和角色的关联
    public void setUserAndRole(Integer userId,Integer[] roleIds ){
        if (roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<String,Integer>();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }


}
